% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Replication "Deconstructing the Yield Curve"
% Crump and Gospodinov (2024)
% Date: 26-JUL-2024
% Function for matching dates
% Called by BR_Table2_BRdata.m and BR_Table2_BRdata_IndMats.m
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function outY = matchDates(datesRef,datesY,Y)

    outY = NaN(numel(datesRef),size(Y,2));

    if datesRef(1) > datesY(1) && datesRef(end) >= datesY(end)
           tmpIdx = find(datesY==datesRef(1));
           Y = Y(tmpIdx:end,:);
           datesY = datesY(tmpIdx:end);    
    elseif datesRef(1) <= datesY(1) && datesRef(end) < datesY(end)
           tmpIdx = find(datesY==datesRef(end));
           Y = Y(1:tmpIdx,:);
           datesY = datesY(1:tmpIdx);
    elseif datesRef(1) > datesY(1) && datesRef(end) < datesY(end)
           tmpIdxStart = find(datesY==datesRef(1));
           tmpIdxEnd = find(datesY==datesRef(end));           
           Y = Y(tmpIdxStart:tmpIdxEnd,:);
           datesY = datesY(tmpIdxStart:tmpIdxEnd);           
    end

    [~,idxY] = intersect(datesRef,datesY);
    outY(idxY,:) = Y;

end

